package com.example.employeemanagement.service.impl;

import com.example.employeemanagement.dto.AttendanceListDto;
import com.example.employeemanagement.dto.AttendancePageQueryDto;
import com.example.employeemanagement.dto.PageResultDto;
import com.example.employeemanagement.entry.Attendance;
import com.example.employeemanagement.entry.Department;
import com.example.employeemanagement.entry.Employee;
import com.example.employeemanagement.mapper.AttendanceMapper;
import com.example.employeemanagement.mapper.DepartmentMapper;
import com.example.employeemanagement.mapper.EmployeeMapper;
import com.example.employeemanagement.service.AttendanceService;
import com.example.employeemanagement.vo.AttendanceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class AttendanceServiceImpl implements AttendanceService {
    
    @Autowired
    private AttendanceMapper attendanceMapper;
    
    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public AttendanceVo createAttendance(AttendanceVo vo) {
        attendanceMapper.insert(vo);
        return vo;
    }

    @Override
    public List<AttendanceListDto> getAllAttendances() {
        // 获取考勤信息
        List<AttendanceVo> attendances = attendanceMapper.selectAll();
        
        // 创建结果列表
        List<AttendanceListDto> result = new ArrayList<>();
        
        // 遍历考勤记录，关联员工和部门信息
        for (AttendanceVo attendance : attendances) {
            // 通过员工ID获取员工信息
            Optional<Employee> employeeOpt = employeeMapper.getEmployeeById(attendance.getEmployeeId());
            
            if (employeeOpt.isPresent()) {
                Employee employee = employeeOpt.get();

                // 获取员工的姓
                String firstName = employee.getFirst_name();

                // 获取员工的名
                String lastName = employee.getLast_name();

                // 全部
                String fullName = lastName + firstName;
                System.out.println("全名 >>> " + fullName);
                
                // 通过部门ID获取部门信息
                Department department = departmentMapper.getDepartmentById(employee.getDepartment_id());
                
                // 创建DTO并设置值
                AttendanceListDto dto = new AttendanceListDto();
                dto.setNickName(fullName);
                dto.setId(attendance.getId());
                dto.setEmployeeId(attendance.getEmployeeId());
                // 从员工实体中获取头像路径
                dto.setAvator(employee.getAvator());
                
                // 设置部门名称
                if (department != null) {
                    dto.setDepartment(department.getDepartment_name());
                } else {
                    dto.setDepartment("未分配部门");
                }
                
                dto.setAttendanceDate(attendance.getAttendanceDate());
                dto.setClockInTime(attendance.getClockInTime());
                dto.setClockOutTime(attendance.getClockOutTime());
                dto.setStatus(attendance.getStatus());
                dto.setRemark(attendance.getRemark());
                
                result.add(dto);
            }
        }
        
        return result;
    }

    @Override
    public Attendance getAttendanceById(int id) {
        System.out.println("考勤记录id" + id);
        Attendance result = attendanceMapper.selectById(id);
        System.out.println("考勤结果" + result);
        return result;
    }

    @Override
    @Transactional
    public AttendanceVo updateAttendance(int id, AttendanceVo vo) {
        // 获取更新前的数据
        Attendance existingRecord = attendanceMapper.selectById(id);
        System.out.println("更新前数据: " + existingRecord);
        System.out.println("提交的数据: " + vo);
        
        vo.setId(id);
        int updatedRows = attendanceMapper.update(vo);
        System.out.println("更新影响行数: " + updatedRows);
        
        if (updatedRows <= 0) {
            // 如果记录存在但未更新，可能是数据类型问题或数据未变化
            if (existingRecord != null) {
                System.out.println("记录存在但未更新，检查数据类型和值是否有实际变化");
                // 尝试强制更新，忽略影响行数
                return vo;
            } else {
                throw new IllegalArgumentException("考勤记录更新失败，记录不存在，ID: " + id);
            }
        }
        return vo;
    }

    @Override
    @Transactional
    public void deleteAttendance(int id) {
        attendanceMapper.delete(id);
    }

    /**
     * 查询用户的所有 记录
     *
     */
    @Override
    public List<Attendance> getAttendancesAllByUserId(int employeeId) {
        List<Attendance> result = attendanceMapper.selectByEmployeeId(employeeId);
        return result;
    }
    
    @Override
    public PageResultDto<AttendanceListDto> pageQuery(AttendancePageQueryDto queryDto) {
        // 参数校验和默认值设置
        if (queryDto.getPageNum() == null || queryDto.getPageNum() < 1) {
            queryDto.setPageNum(1);
        }
        if (queryDto.getPageSize() == null || queryDto.getPageSize() < 1) {
            queryDto.setPageSize(10);
        }
        
        // 计算分页参数
        int offset = (queryDto.getPageNum() - 1) * queryDto.getPageSize();
        int limit = queryDto.getPageSize();
        
        // 查询总记录数
        long total = attendanceMapper.countForPageQuery(
                queryDto.getEmployeeName(),
                queryDto.getEmployeeId(),
                queryDto.getDepartment(),
                queryDto.getStatus());
        
        // 如果没有记录，直接返回空结果
        if (total == 0) {
            return PageResultDto.build(0, queryDto.getPageNum(), queryDto.getPageSize(), new ArrayList<>());
        }
        
        // 查询当前页数据
        List<AttendanceListDto> list = attendanceMapper.pageQuery(
                queryDto.getEmployeeName(),
                queryDto.getEmployeeId(),
                queryDto.getDepartment(),
                queryDto.getStatus(),
                offset,
                limit);
        
        // 构建并返回分页结果
        return PageResultDto.build(total, queryDto.getPageNum(), queryDto.getPageSize(), list);
    }


}